package net.begincode.service;

import net.begincode.enums.StatusEnum;
import net.begincode.mapper.ConfigMapper;
import net.begincode.model.Config;
import net.begincode.model.ConfigExample;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by saber on 2017/9/23.
 */
@Service
public class ConfigService {

    @Resource
    private ConfigMapper configMapper;

    /**
     * 查询服务的所有节点
     * @param serverId
     * @param currentNum
     * @param eachSize
     * @return list 节点
     */
    public List<Config> listServerConfig(Integer serverId, Integer currentNum, Integer eachSize){
        ConfigExample configExample = new ConfigExample();
        ConfigExample.Criteria criteria = configExample.createCriteria();
        criteria.andServerBelongEqualTo(serverId);
        return configMapper.selectByExampleWithRowbounds(configExample, new RowBounds((currentNum - 1) * eachSize, eachSize));
    }

    /**
     * 修改服务节点
     * @param config
     * @param configId
     * @return Integer
     */
    public Integer updateConfig(Config config ,Integer configId){
        ConfigExample configExample = new ConfigExample();
        ConfigExample.Criteria criteria = configExample.createCriteria();
        criteria.andIdEqualTo(configId);
        return configMapper.updateByExample(config,configExample);
    }

    /**
     * 新增节点
     * @param config
     * @return Integer
     */
    public Integer insertConfig(Config config){
        return configMapper.insertSelective(config);
    }

    /**
     * 删除服务节点
     * @param configId
     * @return Integer
     */
    public Integer deleteConfig(Integer configId){
        return configMapper.deleteByPrimaryKey(configId);
    }

    /**
     * 查询服务的节点数
     * @param serverId
     * @return Integer
     */
    public Integer countServerConfig(Integer serverId){
        ConfigExample configExample = new ConfigExample();
        ConfigExample.Criteria criteria = configExample.createCriteria();
        criteria.andServerBelongEqualTo(serverId);
        return configMapper.countByExample(configExample);
    }

    /**
     * 查询服务停用的的节点数
     * @param serverId
     * @return Integer
     */
    public Integer countServerStopConfig(Integer serverId){
        ConfigExample configExample = new ConfigExample();
        ConfigExample.Criteria criteria = configExample.createCriteria();
        criteria.andServerBelongEqualTo(serverId).andStatusEqualTo(Integer.parseInt(StatusEnum.STOP_FLAG.getCode()));
        return configMapper.countByExample(configExample);
    }
}
